package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"

	"ppp/internal/config"
	"ppp/internal/routes"
)

func main() {
	// 初始化数据库连接
	if err := config.InitDatabase(); err != nil {
		log.Fatalf("数据库连接失败: %v\n", err)
	}
	log.Println("数据库连接成功")

	// 创建Gin路由器
	router := gin.Default()

	// 配置CORS中间件
	router.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 设置路由
	routes.SetupRoutes(router)

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    ":8900",
		Handler: router,
	}

	// 启动服务器的goroutine
	go func() {
		log.Println("服务器启动在 http://localhost:8900")
		log.Println("健康检查端点: http://localhost:8900/health")
		log.Println("用户API端点: http://localhost:8900/api/users")
		log.Println("登录端点: http://localhost:8900/api/auth/login")

		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("服务器启动失败: %v\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("正在关闭服务器...")

	// 设置5秒的超时时间来关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("服务器关闭出错: %v\n", err)
	}

	log.Println("服务器已优雅关闭")
}
